package com.example.basic_config.advice;

import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * @description 全局处理
 * @author ljw
 * @date 2021/9/2 7:29
 */
@ControllerAdvice
public class MyHandleAdvice {

    /**
     * 全局异常处理（指定异常类型）
     * @param
     * @author ljw
     * @date 2021/9/2 7:36
     */
    @ExceptionHandler(value = Exception.class)
    public ModelAndView exception(Exception exception, WebRequest request) {
        ModelAndView modelAndView = new ModelAndView("error");
        modelAndView.addObject("errorMessage", exception.getMessage());
        return modelAndView;
    }

    /**
     * 初始化全局数据
     * @param model 前后端传递参数
     * @author ljw
     * @date 2021/9/2 7:39
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("msg", "额外信息");
    }

    /**
     * 全局数据预处理
     * @param webDataBinder 自动绑定前台请求参数到 Model中
     * @author ljw
     * @date 2021/9/2 7:47
     */
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        //去掉前台参数中的id
        webDataBinder.setDisallowedFields("id");
    }
}
